package org.uni_hi.muus.server.util;

import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotFoundException;
import javax.microedition.rms.RecordStoreNotOpenException;

public abstract class AbstractRecordStore {
	protected RecordStore _rs=null;

	private String _rsName=null;
	
	protected AbstractRecordStore(String rsName){
		this._rsName=rsName;
	}
	
	protected void openRecordStore(){
		if(_rs==null){
			try {
				_rs=RecordStore.openRecordStore(_rsName, true, RecordStore.AUTHMODE_PRIVATE,true);
			} catch (RecordStoreNotFoundException e) {
				e.printStackTrace();
			} catch (RecordStoreException e) {
				e.printStackTrace();
			}
		}
	}
	
	protected void closeRecordStore(){
		if(_rs!=null){
			try {
				_rs.closeRecordStore();
				_rs=null;
			} catch (RecordStoreNotOpenException e) {
				e.printStackTrace();
			} catch (RecordStoreException e) {
				e.printStackTrace();
			}
		}
	}

	protected String getData(int pos){
		String rd = "";
		try {
			openRecordStore();
			rd=new String(_rs.getRecord(pos));
		} catch (RecordStoreNotOpenException e) {
			e.printStackTrace();
		} catch (InvalidRecordIDException e) {
			e.printStackTrace();
		} catch (RecordStoreException e) {
			e.printStackTrace();
		}finally{
			closeRecordStore();	
		}	
		return rd;
	}

	protected int setData(int pos,String rd){
		byte[] bytes=rd.getBytes();
		try {
			openRecordStore();
			_rs.setRecord(pos, bytes, 0, bytes.length);
		} catch (RecordStoreNotOpenException e) {
			e.printStackTrace();
		} catch (InvalidRecordIDException e) {
			try {
				pos=_rs.addRecord(bytes, 0, bytes.length);
			} catch (RecordStoreNotOpenException e1) {
				e1.printStackTrace();
			} catch (RecordStoreFullException e1) {
				e1.printStackTrace();
			} catch (RecordStoreException e1) {
				e1.printStackTrace();
			}
		} catch (RecordStoreFullException e) {
			e.printStackTrace();
		} catch (RecordStoreException e) {
			e.printStackTrace();
		}finally{
			closeRecordStore();
		}	
		return pos;
	}
}
